import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:meco/common/models/chat_message_model.dart';
import 'package:meco/common/models/chat_room_model.dart';
import 'package:meco/common/models/user_model.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class ChatController extends GetxController {
  ChatController();

  // 聊天室
  late ChatRoom chatRoom;

  // 是否是群聊
  final RxBool isGroupChat = false.obs;

  // 聊天对象（单聊时使用）
  final Rx<User?> chatTarget = Rx<User?>(null);

  // 群聊成员
  final RxList<User> groupMembers = <User>[].obs;

  // 消息列表
  final RxList<ChatMessage> messages = <ChatMessage>[].obs;

  // 消息输入控制器
  late TextEditingController messageInputController;

  // 是否正在加载消息
  final RxBool isLoading = true.obs;

  // 聊天室标题
  final RxString chatTitle = "".obs;

  // 仓库
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();
  final ChatMessageRepository _chatMessageRepository = ChatMessageRepository();
  final UserRepository _userRepository = UserRepository();

  // 消息滚动控制器
  late ScrollController scrollController;

  // 用于文本输入的控制器
  final TextEditingController messageController = TextEditingController();
  // 聚焦节点
  final FocusNode focusNode = FocusNode();

  // 初始化数据
  _initData() async {
    isLoading.value = true;

    try {
      // 获取聊天室参数
      final arguments = Get.arguments as Map<String, dynamic>?;
      if (arguments != null && arguments.containsKey('chatRoom')) {
        chatRoom = arguments['chatRoom'] as ChatRoom;

        // 设置群聊标志
        isGroupChat.value = chatRoom.isGroup;

        // 设置聊天标题
        chatTitle.value = chatRoom.name;

        // 加载聊天记录
        await loadMessages();

        // 加载用户信息
        await loadUserInfo();

        // 标记所有消息为已读
        markMessagesAsRead();
      }
    } catch (e) {
      print('初始化聊天页面失败: $e');
    } finally {
      isLoading.value = false;
      update(["chat"]);
    }
  }

  // 加载聊天记录
  Future<void> loadMessages() async {
    try {
      final messageList = await _chatMessageRepository.getMessagesByChatRoomId(
        chatRoom.id!,
        limit: 100,
      );

      // 按时间排序（从早到晚）
      messageList.sort((a, b) => a.createdAt.compareTo(b.createdAt));

      messages.value = messageList;

      // 滚动到最新消息
      Future.delayed(Duration(milliseconds: 300), () {
        if (scrollController.hasClients && messages.isNotEmpty) {
          scrollController.animateTo(
            scrollController.position.maxScrollExtent,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    } catch (e) {
      print('加载聊天记录失败: $e');
    }
  }

  // 加载用户信息
  Future<void> loadUserInfo() async {
    final UserService userService = Get.find<UserService>();
    final currentUserId = userService.currentUser.value!.id!;

    try {
      if (isGroupChat.value) {
        // 加载群聊成员信息
        for (var userId in chatRoom.memberIds) {
          final user = await _userRepository.getUserById(userId);
          if (user != null) {
            groupMembers.add(user);
          }
        }
      } else {
        // 单聊：找出对方用户
        for (var userId in chatRoom.memberIds) {
          if (userId != currentUserId) {
            final user = await _userRepository.getUserById(userId);
            if (user != null) {
              chatTarget.value = user;
              // 更新聊天标题为对方用户名
              chatTitle.value = user.nickname ?? user.username ?? 'User';
            }
            break;
          }
        }
      }
    } catch (e) {
      print('加载用户信息失败: $e');
    }
  }

  // 标记消息为已读
  Future<void> markMessagesAsRead() async {
    try {
      final UserService userService = Get.find<UserService>();
      final currentUserId = userService.currentUser.value!.id!;

      print('标记聊天室 ${chatRoom.id} 的消息为已读');
      await _chatMessageRepository.markAllMessagesAsRead(
        chatRoom.id!,
        currentUserId,
      );
    } catch (e) {
      print('标记消息已读失败: $e');
    }
  }

  // 发送消息
  Future<void> sendMessage() async {
    if (messageController.text.trim().isEmpty) return;

    try {
      final UserService userService = Get.find<UserService>();
      final currentUserId = userService.currentUser.value!.id!;

      final message = ChatMessage(
        chatRoomId: chatRoom.id!,
        senderId: currentUserId,
        content: messageController.text.trim(),
        createdAt: DateTime.now(),
      );

      final messageId = await _chatMessageRepository.sendMessage(message);

      if (messageId > 0) {
        // 清空输入框
        messageController.clear();

        // 确保更新聊天室最后一条消息信息
        await _chatRoomRepository.updateLastMessage(
          chatRoom.id!,
          message.content,
          message.createdAt,
        );

        // 重新加载消息
        await loadMessages();

        // 强制刷新数据，确保消息发送后UI即时更新
        update(["chat"]);
      }
    } catch (e) {
      print('发送消息失败: $e');
    }
  }

  // 判断消息是否来自当前用户
  bool isMessageFromCurrentUser(ChatMessage message) {
    final UserService userService = Get.find<UserService>();
    return message.senderId == userService.currentUser.value!.id!;
  }

  // 获取消息发送者信息
  User? getMessageSender(ChatMessage message) {
    if (isGroupChat.value) {
      return groupMembers.firstWhereOrNull(
        (user) => user.id == message.senderId,
      );
    } else {
      final UserService userService = Get.find<UserService>();

      if (message.senderId == userService.currentUser.value!.id!) {
        return userService.currentUser.value;
      } else {
        return chatTarget.value;
      }
    }
  }

  // 举报聊天用户
  void reportUser() {
    if (isGroupChat.value || chatTarget.value == null) return;

    final User user = chatTarget.value!;

    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报聊天用户: ${user.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 清空聊天记录
        try {
          // 清空消息列表
          messages.clear();

          // 删除数据库中的所有消息
          final db = await Get.find<DatabaseService>().database;
          await db.delete(
            'chat_messages',
            where: 'chat_room_id = ?',
            whereArgs: [chatRoom.id!],
          );

          // 显示成功提示
          EasyLoading.showSuccess('All messages have been removed');

          // 更新UI
          update(["chat"]);
        } catch (e) {
          print('清空聊天记录失败: $e');
        }

        return true;
      },
    );
  }

  // 举报群聊
  void reportGroup() {
    if (!isGroupChat.value) return;

    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报群聊: ${chatRoom.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 退出群聊
        try {
          final UserService userService = Get.find<UserService>();
          final currentUserId = userService.currentUser.value!.id!;

          // 从群聊成员中移除当前用户
          ChatRoom updatedRoom = chatRoom.copyWith(
            memberIds:
                chatRoom.memberIds.where((id) => id != currentUserId).toList(),
          );
          await _chatRoomRepository.updateChatRoom(updatedRoom);

          // 显示成功提示
          EasyLoading.showSuccess('You have left the group chat');

          // 返回上一页
          Future.delayed(Duration(seconds: 1), () {
            Get.back();
          });
        } catch (e) {
          print('退出群聊失败: $e');
        }

        return true;
      },
    );
  }

  @override
  void onInit() {
    super.onInit();

    // 初始化控制器
    messageInputController = TextEditingController();
    scrollController = ScrollController();

    // 从参数获取聊天室信息
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    messageInputController.dispose();
    scrollController.dispose();
    messageController.dispose();
    focusNode.dispose();
    super.onClose();
  }
}
